package cn.ecut.dzy.interview;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @program: java-interview
 * @description:三个线程分别打印 A，B，C，要求这三个线程一起运行，打印 n 次，输出形如“ABCABCABC....”的字符串
 * @author: DingZhenYun
 * @create: 2021-10-25 11:48
 **/
class PrintABC {
    private int times; // 控制打印次数

    private int state; // 当前状态值：保证三个线程之间交替打印
    private Lock lock = new ReentrantLock();

    public PrintABC(int times) {
        this.times = times;
    }

    void printLetter(String name, int targetNum) {
        for (int i = 0; i < times; ) {
            lock.lock();
            if (state % 3 == targetNum) {
                state++;
                i++;
                System.out.print(name);
            }
            lock.unlock();
        }
    }
}



public class PrintABCUsingLock {
    public static void main(String[] args) {
    }

    private static void m1() {
        PrintABC loopThread = new PrintABC(1);
        new Thread(() -> {
            loopThread.printLetter("A", 0);
        }, "A").start();
        new Thread(() -> {
            loopThread.printLetter("B", 1);
        }, "B").start();
        new Thread(() -> {
            loopThread.printLetter("C", 2);
        }, "C").start();
    }

}
